package com.jetpackframework.virtual;

import android.text.TextUtils;

import com.jetpackframework.ContextUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import dalvik.system.PathClassLoader;

/**
 * 指定目录的类加载器
 */
public class VirtualDexClassLoader extends PathClassLoader {
    private final ClassLoader parent;
    /**目录
     *
     * @param dexPath  dex文件名称  多个以：隔开
     * @param optimizedDir   dex文件解压后的缓存目录
     * @param librarySearchPath
     * @param parent  父类加载器
     */
    public VirtualDexClassLoader(String dexPath, File optimizedDir, String librarySearchPath, ClassLoader parent) {
        super("", librarySearchPath, ClassLoader.getSystemClassLoader());
        this.parent = parent;
        injectDexPath(dexPath,optimizedDir,parent);

    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class<?> cl = null;
        try {
            cl = super.findClass(name);
        }catch (ClassNotFoundException e){
            cl = null;
        }
        if (cl == null){
            return parent.loadClass(name);
        }
        return cl;
    }
    private static void injectDexPath(String dexPath, File optimizedDir, ClassLoader parent) {
        List<File> dexFile = new ArrayList<>();
        for (String dex : dexPath.split(":")){
            if (TextUtils.isEmpty(dex)){
                continue;
            }
            dexFile.add(new File(dex));
        }
        if (!dexFile.isEmpty()){
            ClassLoaderUtil.injectDexesInternal(dexFile,optimizedDir,parent);
        }
    }
}
